package LeetcodeTest_seventeen;
//最长回文子串
public class longestPalindrome
{
    public static void main(String[] args)
    {
        String str="ccc";
        System.out.println(solution.longestPalindrome(str));
    }
}
class solution
{
    public static String longestPalindrome(String s)
    {
        if (s.length()==0)
            return "";
        if (s.length()==1)
            return s.charAt(0)+"";
        int i,j,k,l,m;
        int maxLength,begin,end;
        maxLength=begin=end=0;
        String answer;
        for (i=0;i<s.length()-1;i++)
        {
            //分两种情况，第一种aa,第二种aba
            //1、连续两个字符构成回文，然后向两边寻找，同时记录当前找到的最长的回文序列长度和起始位置
            if(s.charAt(i)==s.charAt(i+1))
            {
                j=i-1;
                k=i+2;
                while(j>=0&&k<s.length()&&s.charAt(j)==s.charAt(k))
                {
                    j--;
                    k++;
                }
                if(maxLength<(k-j+1))
                {
                    maxLength=k-j+1;
                    begin = j + 1;
                    end = k - 1;
                }
            }
            //2、aba这种情况，也是向该序列的两边寻找
            if(i-1>=0&&s.charAt(i-1)==s.charAt(i+1)&&i+1<s.length())
            {
                l=i-2;
                m=i+2;
                while(l>=0&&m<s.length()&&s.charAt(l)==s.charAt(m))
                {
                    l--;
                    m++;
                }
                if(maxLength<(m-l+1))
                {
                    maxLength=m-l+1;
                    begin = l + 1;
                    end = m - 1;
                }
            }
        }
        answer=s.substring(begin,end+1);
        return answer;
    }
}